<template>
  <div class="published-container">
    <!-- 顶部状态筛选 -->
    <el-affix :offset="0">
      <el-tabs 
        v-model="activeStatus" 
        class="status-tabs"
        @tab-change="filterProductsByStatus"
      >
        <el-tab-pane label="在卖" name="在卖"></el-tab-pane>
        <el-tab-pane label="草稿" name="草稿"></el-tab-pane>
        <el-tab-pane label="交易中" name="交易中"></el-tab-pane>
        <el-tab-pane label="已下架" name="已下架"></el-tab-pane>
      </el-tabs>
    </el-affix>

    <!-- 商品列表 -->
    <el-scrollbar class="product-scrollbar" @scroll="handleScroll">
      <div class="product-list">
        <el-card 
          v-for="product in filteredProducts" 
          :key="product.id" 
          class="product-card"
          shadow="hover"
        >
          <div class="product-content">
            <el-image 
              class="product-image" 
              :src="product.image || 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png'"
              fit="cover"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            
            <div class="product-info">
              <div class="product-name">{{ product.name }}</div>
              <div class="product-meta">
                <div class="product-price">¥{{ product.price }}</div>
                <el-tag :type="getStatusType(product.status)" size="small">
                  {{ reverseStatusMap[product.status] || '未知状态' }}
                </el-tag>
              </div>
              <div class="product-actions">
                <el-button 
                  v-if="reverseStatusMap[product.status] === '在卖'"
                  type="warning" 
                  size="small" 
                  @click="performAction('改价', product.id)"
                >
                  改价
                </el-button>
                <el-button
                  v-if="reverseStatusMap[product.status] !== '交易中'"
                  type="primary" 
                  size="small" 
                  @click="performAction('编辑', product.id)"
                >
                  编辑
                </el-button>
                <el-button 
                  v-if="reverseStatusMap[product.status] === '在卖'"
                  type="danger" 
                  size="small" 
                  @click="performAction('下架', product.id)"
                >
                  下架
                </el-button>
                <el-button 
                  v-if="reverseStatusMap[product.status] === '已下架' || reverseStatusMap[product.status] === '草稿'"
                  type="success" 
                  size="small" 
                  @click="performAction('上架', product.id)"
                >
                  上架
                </el-button>
                <el-button
                  v-if="reverseStatusMap[product.status] !== '交易中'"
                  type="danger" 
                  size="small" 
                  @click="performAction('删除', product.id)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 加载更多 -->
        <div v-if="loading" class="loading-more">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        <div v-if="!hasMore" class="no-more-data">
          没有更多数据了
        </div>
      </div>
    </el-scrollbar>

    <!-- 改价对话框 -->
<el-dialog v-model="showPriceDialog" title="价格修改" width="30%">
  <el-form>
    <el-form-item label="原价">
      <span>¥{{ products.find(p =>p.id === currentProductId)?.price || 0 }}</span>
    </el-form-item>
    <el-form-item label="新价格">
      <el-input v-model="priceReduction" placeholder="请输入新价格" type="number">
        <template #prefix>¥</template>
      </el-input>
    </el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="showPriceDialog = false">取消</el-button>
      <el-button type="primary" @click="performPriceReduction">确定</el-button>
    </span>
  </template>
</el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Picture, Loading } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import apiClient from '@/utils/request'
// 商品数据
const products = ref([])
const displayedProducts = ref([])
const activeStatus = ref('在卖')
const currentPage = ref(1)
const itemsPerPage = ref(10)
const loading = ref(false)
const hasMore = ref(true)

// 改价相关状态
const showPriceDialog = ref(false)
const priceReduction = ref('')
const currentProductId = ref(null)

// 状态映射
const statusMap = {
  '在卖': 1,
  '草稿': 0,
  '交易中': 2,
  '已下架': 4
}

const reverseStatusMap = {
  0: '草稿',
  1: '在卖',
  2: '交易中',
  3: '已完成',
  4: '已下架',
  5: '已关闭'
}

// 根据状态筛选商品
const filteredProducts = computed(() => {
  return displayedProducts.value.filter(p => {
    const statusText = reverseStatusMap[p.status] || '未知状态'
    return statusText === activeStatus.value
  })
})

// 根据状态获取标签类型
const getStatusType = (statusCode) => {
  const status = reverseStatusMap[statusCode] || '未知状态'
  const types = {
    '在卖': 'success',
    '草稿': 'info',
    '已下架': 'danger',
    '交易中': 'warning',
    '已完成': '',
    '已关闭': 'danger'
  }
  return types[status] || ''
}

// 获取商品数据
const loadProducts = async () => {
  try {
    loading.value = true
    const token = localStorage.getItem('access_token')
    if (!token) {
      ElMessage.error('请先登录')
      return
    }

    const response = await apiClient.get('/api/products/seller/', {
      params: {
        page: currentPage.value
      }
    })

    if (response.data && response.data.results && Array.isArray(response.data.results)) {
      const newProducts = response.data.results.map(item => ({
        ...item,
        id: item.id,
        status: item.status,
        image: item.images?.length > 0 ? item.images[0].url : '',
        name: item.name || '未命名商品',
        price: item.price || 0,
        product_code: item.product_code
      }))

      if (currentPage.value === 1) {
        products.value = newProducts
      } else {
        products.value = [...products.value, ...newProducts]
      }
      
      displayedProducts.value = products.value
      hasMore.value = response.data.next !== null
    } else {
      products.value = []
      displayedProducts.value = []
      hasMore.value = false
    }
  } catch (error) {
    console.error('获取商品数据失败:', error)
    ElMessage.error('获取商品数据失败，请稍后重试')
    if (error.response?.status === 401) {
      localStorage.removeItem('access_token')
      window.location.href = '/login'
    }
  } finally {
    loading.value = false
  }
}

// 状态切换
const filterProductsByStatus = (status) => {
  currentPage.value = 1
  loadProducts()
}

// 打开改价对话框
const openPriceDialog = (productId) => {
  currentProductId.value = productId
  priceReduction.value = ''
  showPriceDialog.value = true
}

// 执行改价操作
const performPriceReduction = async () => {
  try {
    const product = products.value.find(p => p.id === currentProductId.value)
    if (!product) return

    const token = localStorage.getItem('access_token')
    if (!token) {
      ElMessage.error('请先登录')
      return
    }

    const newPrice = parseFloat(priceReduction.value)
    if (isNaN(newPrice) || newPrice <= 0) {
      ElMessage.error('请输入有效的价格')
      return
    }

    // 调用改价API
    const response = await apiClient.post(
      `/api/products/seller/${product.product_code}/change-price/`,
      { new_price: newPrice })

    if (response.data) {
      ElMessage.success('商品改价成功')
      // 更新本地商品价格
      product.price = response.data.new_price
      showPriceDialog.value = false
      // 重新加载商品列表以确保数据同步
      await loadProducts()
    }
  } catch (error) {
    const errorMsg = error.response?.data?.error || error.message
    ElMessage.error(`改价失败: ${errorMsg}`)
    if (error.response?.status === 401) {
      localStorage.removeItem('access_token')
      window.location.href = '/login'
    }
  }
}

// 执行操作
const performAction = async (action, productId) => {
  try {
    const product = products.value.find(p => p.id === productId)
    if (!product) return

    const token = localStorage.getItem('access_token')
    if (!token) {
      ElMessage.error('请先登录')
      return
    }

    if (action === '改价') {
      openPriceDialog(productId)
      return
    }

    await ElMessageBox.confirm(
      `确定要${action}该商品吗?`,
      '操作确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    let response

    if (action === '编辑') {
      window.location.href = `/edit?product_code=${product.product_code}`
      return
    } else if (action === '下架') {
      response = await apiClient.post(
        `/api/products/seller/${product.product_code}/unpublish/`,
        {})
    } else if (action === '上架') {
      response = await apiClient.post(
        `/api/products/seller/${product.product_code}/republish/`,
        {})
    } else if (action === '删除') {
      response = await apiClient.delete(
        `/api/products/seller/${product.product_code}/`
      )
      // 从本地列表中移除已删除的商品
      products.value = products.value.filter(p => p.id !== productId)
      displayedProducts.value = displayedProducts.value.filter(p => p.id !== productId)
      ElMessage.success('商品删除成功')
      return
    }

    // 更新本地状态
    if (response && response.data) {
      const updatedStatus = response.data.status
      product.status = updatedStatus
      ElMessage.success(`${action}操作成功`)
      loadProducts()
    }
  } catch (error) {
    if (error !== 'cancel') {
      const errorMsg = error.response?.data?.message || error.message
      ElMessage.error(`操作失败: ${errorMsg}`)
      if (error.response?.status === 401) {
        localStorage.removeItem('access_token')
        window.location.href = '/login'
      }
    }
  }
}

// 滚动加载更多
const handleScroll = ({ scrollTop, clientHeight, scrollHeight }) => {
  const isNearBottom = scrollHeight - scrollTop <= clientHeight + 50
  
  if (isNearBottom && !loading.value && hasMore.value) {
    currentPage.value++
    loadProducts()
  }
}

// 初始化加载
onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.published-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
}

.status-tabs {
  background-color: var(--el-bg-color);
  padding: 0 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.status-tabs :deep(.el-tabs__header) {
  margin: 0;
}

.status-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

.product-scrollbar {
  flex: 1;
  padding: 20px;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.product-card {
  width: 100%;
  transition: all 0.3s;
  border-radius: 8px;
}

.product-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.1);
}

.product-content {
  display: flex;
  gap: 15px;
}

.product-image {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  flex-shrink: 0;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-fill-color-light);
  color: var(--el-text-color-placeholder);
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
}

.product-price {
  font-size: 18px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.product-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 10px;
}

.loading-more {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: var(--el-text-color-secondary);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.no-more-data {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: var(--el-text-color-secondary);
}
</style>